package com.yhy.common.config;

import org.apache.commons.lang3.StringUtils;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.springframework.stereotype.Component;

/**
 * <br>
 * <b>功能：</b><br>
 * <b>作者：</b>yanghuiyuan<br>
 * <b>日期：</b> 2020/3/18 <br>
 * <b>版权所有：<b>版权所有(C) 2020<br>
 */
@Component("customJasyptStringEncryptor")
public class CustomJasyptStringEncryptor implements StringEncryptor {

    private static String encryptKey = "";
    public CustomJasyptStringEncryptor() {
        if(StringUtils.isBlank(this.encryptKey)) {
            this.encryptKey = EnvConfig.getValueByPropertyName("spring.datasource.druid.connect-properties.key");
        }
    }

    public CustomJasyptStringEncryptor(String encryptKey) {
        if(StringUtils.isBlank(this.encryptKey)) {
            this.encryptKey = encryptKey;
        }
    }

    @Override
    public String encrypt(String value) {
        if(StringUtils.isBlank(value)) {
            return "";
        }
        if(value.startsWith("ENC(")) {
            return value;
        }
        return "ENC(" + getJasyptStringEncryptor().encrypt(value) + ")";
    }

    @Override
    public String decrypt(String value) {
        if(StringUtils.isBlank(value)) {
            return "";
        }
        if(!value.startsWith("ENC(")) {
            return value;
        }
        value = value.replace("ENC(","");
        value = value.substring(0,value.length()-1);
        return getJasyptStringEncryptor().decrypt(value);
    }

    private StringEncryptor getJasyptStringEncryptor() {
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();
        // 解密的算法，需同加密算法相同
        config.setAlgorithm("PBEWithMD5AndDES");
        //解密的密钥，需同加密密钥相同
        config.setPassword(encryptKey);
        standardPBEStringEncryptor.setConfig(config);
        return standardPBEStringEncryptor;
    }

}
